'''
author:        Wang Chenyang <cy-wang21@mails.tsinghua.edu.cn>
date:          2024-09-23
Copyright © Department of Physics, Tsinghua University. All rights reserved

Resolve and save markdown files
'''

from datetime import datetime
from .common import ALL_FIELDS


def parse_markdown_file(fname, is_old_format=False):
    ''' Resolve data from markdown files
        Rule: if begin with ####, create new record,
              else, read the beginning keywords, and save to dict
    '''
    resolved_items = []

    with open(fname, "r") as fp:
        lines = fp.readlines()
        current_record = {}
        for line in lines:
            # Check if line starts with ####, indicating a new record
            if line.startswith("####"):
                if current_record:  # If there's already a record, append it to the list
                    resolved_items.append(current_record)
                    current_record = {}

                # Check if the title has an exclamation mark
                title = line[5:].strip()
                current_record["highlight"] = True if title.startswith("!") else False
                current_record["title"] = title.replace("!", "").strip()

            # If line starts with a keyword, extract it and its value
            elif ":" in line:
                keyword, value = line.split(":", 1)
                keyword = keyword.strip()
                keyword = keyword.lower()

                if keyword not in ALL_FIELDS:
                    print("Key error!", "key:", keyword, "title:", current_record['title'])
                    assert 0

                # Special handling for certain keywords
                if is_old_format:
                    if keyword == "link":
                        current_record["url"] = value.strip()
                    elif keyword == "date":
                        date_obj = datetime.strptime(value.strip(), "%a, %d %b %Y %H:%M:%S %z")
                        current_record["date"] = date_obj.strftime("%Y-%m-%d")
                    elif keyword == 'kw':
                        current_record["keywords"] = value.strip()
                    else:
                        current_record[keyword] = value.strip()
                else:
                    current_record[keyword] = value.strip()

        # Append the last record if it's not empty
        if current_record:
            resolved_items.append(current_record)

    return resolved_items


def save_to_markdown(all_literatures: list[dict]) -> str:
    ''' Get markdown string from all literatures '''
    all_string = ""
    for item in all_literatures:
        all_keys = list(item.keys())
        all_keys.sort(key=lambda curr_key: ALL_FIELDS.index(curr_key))

        curr_item_str = "#### "
        if 'highlight' in all_keys:
            if item['highlight']:
                curr_item_str += "! "

        # 1. add title
        curr_item_str += item['title'] + '\n'

        # 2. add other items
        for curr_key in all_keys:
            if curr_key == 'title':
                continue
            elif curr_key == 'highlight':
                continue
            curr_item_str += curr_key + ": " + item[curr_key] + '\n\n'

        all_string += curr_item_str

    return all_string
